package com.ld.shieldsb.annotation.validation.idCard;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.lang3.StringUtils;

import com.ld.shieldsb.common.core.validate.ValidateUtil;

public class IDCardValidator implements ConstraintValidator<IDCard, String> {

    // 默认值_false，用于接收注解上自定义的 required
    private boolean required = false;

    // 1、初始化方法：通过该方法我们可以拿到我们的注解
    public void initialize(IDCard constraintAnnotation) {

        required = constraintAnnotation.required();
    }

    // 2、逻辑处理
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 2.1、如果允许为空的话，直接返回结果
        if (required) {
            if (StringUtils.isEmpty(value)) {
                return true;
            } else {
                return ValidateUtil.checkIdCard(value);
            }
        } else {
            if (StringUtils.isEmpty(value)) {
                return false;
            } else {
                return ValidateUtil.checkIdCard(value);
            }
        }
    }

}